/*eslint-disable*/
//本文件只打包common/js/下所有js文件
const fs = require('fs')
const fsPromises = fs.promises
const path = require('path')
const babel = require('@babel/core')
//设置一个白名单，主要用于不babel编译第三方插件，防止打出问题
const whiteFileList = [
  'vant',
  // 'vue.min',
  'eruda.min',
  'aliplayer',
  'jweixin'
]

//必须按数组中的文件顺序打包，因为页面上js之间存在依赖关系
const sort = ['vue', 'vant', 'storage', 'common', 'utils', 'http', 'jweixin']

let dir = path.resolve(path.dirname(__dirname) + '/common/js')

//其他js文件，依次追加到文件末尾
let fileList = fs.readdirSync(dir)

//找到所有的js文件
let findScript = fileList.filter(
  item => path.extname(item) === '.js' && !item.includes('vendor')
)
//排序
let sortFileList = []
//找出排序中的
sort.forEach(item => {
  let scriptFind = findScript.find(script => script.includes(item))
  if (scriptFind) sortFileList.push(scriptFind)
})

sortFileList = [
  ...sortFileList,
  ...findScript.filter(script => !sortFileList.includes(script))
]

let tasks = []

//整合所有文件的内容
let allScriptStr = sortFileList.forEach(script => {
  //如果是在白名单中的文件，就不编译了，其他js编译一下
  let isWhite = whiteFileList.some(item => script.includes(item))
  let fileContent = fs.readFileSync(path.resolve(dir, script), {
    encoding: 'utf-8'
  })

  tasks.push(!isWhite ? babelTransform(fileContent) : fileContent)
})

Promise.all(tasks).then(built => {
  fs.writeFileSync(
    path.resolve(dir, 'vendor.min.js'),
    '/*eslint-disable*/\n' + built.join('\n')
  )
})

//babel编译压缩js代码
async function babelTransform(scriptStr) {
  return babel.transform(scriptStr, {
    presets: [
      [
        'minify',
        {
          infinity: true
        }
      ]
    ], //压缩
    plugins: ['transform-object-assign'], //编译object.assign
    comments: false //去注释
  }).code
}
